package cn.shangjia.shop.servlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.shangjia.common.exceptions.Logger;
import cn.shangjia.shop.config.Constants;
import cn.shangjia.shop.config.ShopConfig;
import cn.shangjia.shop.log.ShopLoggerFactory;
import cn.shangjia.shop.service.impl.common.CommonService;

/**
 * 商家网-商铺-基础数据容器.
 *
 * @author <a href="mailto:wangxin@knet.cn">wangxin</a>
 * @version 1.0, 2011-11-08 16:54:13
 * @since 1.0
 */
public class SystemListener implements ServletContextListener {
	
    private final static Logger logger = ShopLoggerFactory.getLogger(SystemListener.class);
    private final static String name = "商家网-商铺服务-基础数据容器";
    
	public void contextDestroyed(ServletContextEvent sce) {
		logger.info(" 停止[ "+name+" ]");
	}

	public void contextInitialized(ServletContextEvent sce) {
		logger.info(" 开始启动 [ "+name+" ]");
		
		try {
			logger.info(" 启动 spring 容器");
			WebApplicationContext wctx = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
			
			logger.info(" 初始化 商铺系统设置 ");
			ShopConfig shopConfig = wctx.getBean(ShopConfig.class);
			sce.getServletContext().setAttribute(Constants.SHOP_CONFIG, shopConfig);
			
			logger.info(" 初始化 商家网系统设置 缓冲池");
			CommonService commonService = wctx.getBean(CommonService.class);
			commonService.fillSiteSetting();
			
			logger.info(" 初始化 商家网分类映射表 缓冲池");
			commonService.fillGBT_MAP();  
			
			logger.info(" 初始化 商家网缓存[]");
			logger.info(" 将访问量最多的["  , shopConfig.getVisitTopNum() , "]家商铺 进行缓存预加载  ... ");
			commonService.initShopSystem(shopConfig.getVisitTopNum());
			
			logger.info(" 成功启动 [ "+name+" ]");
		} catch (Exception e) {
			logger.error(e, "启动 [ "+name+" ]有异常发生 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
		}
		
	}
}
